// 数据列表
const list = document.querySelector('.list')

// UID
const UID = localStorage.getItem('UID')

// 表格控制栏
const first = document.querySelector('.first')
const last = document.querySelector('.last')
const next = document.querySelector('.next')
const theLast = document.querySelector('.theLast')
const paged = document.querySelector('.paged')
const pageSum = document.querySelector('.controlTable select')
const allPage = document.querySelector('.allPage')

// 页码
let page = 1
let pageNumber = 5
// 记录最大页数
let maxPage = 0

async function getAllCourse() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Student/CourseSelection/getAllCourse',
    params: {
      UID,
      page,
      pageNumber
    }
  })).data.data
  const htmlStr = await Promise.all(result.map(async e => {
    // 获取教师名字
    const name = (await axios({
      url: 'http://127.0.0.1:8080/Teacher/CourseManagement/getTeacherNameById',
      params: {
        UID: e.teacher
      }
    })).data.data
    const degreeValueArr = e.degreeDemand
    let degreeArr = ''
    for (let i = 0; i < degreeValueArr.length; i++) {
      const degree = degreeValueArr[i]
      if (degree.indexOf("1") !== -1) {
        degreeArr += ' 专科'
      } else if (degree.indexOf("2") !== -1) {
        degreeArr += ' 本科'
      } else if (degree.indexOf("3") !== -1) {
        degreeArr += ' 硕士研究生'
      } else if (degree.indexOf("4") !== -1) {
        degreeArr += ' 博士研究生'
      } else if (degree.indexOf("5") !== -1) {
        degreeArr += ' 博士后研究生'
      }
    }
    return `
      <tr data-id="${e.id}">
        <td>${e.id}</td>
        <td>${e.name}</td>
        <td>${e.credit}</td>
        <td>${name}</td>
        <td>${e.day}</td>
        <td>${e.time}</td>
        <td>${e.location}</td>
        <td>${e.constantTime}</td>
        <td>${e.instructionalMethod}</td>
        <td class="degreeBox">${degreeArr}</td>
      </tr>
    `
  }))
  list.innerHTML = htmlStr.join('')
}

getAllCourse()


async function getPageSum() {
  const result = (await axios({
    url: 'http://127.0.0.1:8080/Student/CourseSelection/getPageSum',
    params: {
      UID,
      pageNumber
    }
  })).data.data
  allPage.innerHTML = result
}

getPageSum()


// 表格控件监听
first.addEventListener('click', () => {
  page = 1
  getAllCourse(page, pageNumber)
})

last.addEventListener('click', () => {
  if (page > 1) {
    --page
    getAllCourse()
  }
})

next.addEventListener('click', () => {
  getPageSum()
  if (page < maxPage) {
    ++page
    getAllCourse()
  }
})

theLast.addEventListener('click', () => {
  page = maxPage
  getAllCourse()
})

pageSum.addEventListener('change', () => {
  pageNumber = pageSum.value
  page = 1
  getAllCourse()
  getPageSum()
})

paged.addEventListener('change', () => {
  page = paged.value
  // 限定page范围
  page = page > maxPage ? maxPage : page
  page = page < 1 ? 1 : page
  getAllCourse()
})